package com.zbf.生成图片;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author: LCG
 * @Date: 2022-01-26 20:25:59
 * @description:  通过画布生成图片
 **/
public class CreateImage {
    public static void main(String[] args) {

        BufferedImage bufferedImage = loadImageUrl("https://assets.xingqutuan.cn/9527-122.jpg");
        BufferedImage logo = loadImageUrl("https://assets.xingqutuan.cn/9527-124.png");
        BufferedImage qrCodeImage = loadImageUrl("https://assets.xingqutuan.cn/9527-124.png");

        BufferedImage bufferedImage1 = mergeImageToNew(bufferedImage,logo,qrCodeImage,540, 960,1070);

        writeImageLocal("E:\\IMAGE\\5555.png",bufferedImage1);

    }

    //导入网络图片到缓冲区
    public static BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {

        }
        return null;
    }

    //将一个图片插入新的图片
    public static BufferedImage mergeImageToNew(BufferedImage img1,BufferedImage logoImage,BufferedImage qrCodeImage,int width,int height,int huaBuHeight){
        Graphics2D graphics2D = null;
        // 生成新图片 width 画布的宽度，huaBuHeight画布的高度
        BufferedImage destImage = new BufferedImage(width, huaBuHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destImage.createGraphics();
        //设置背景色
        graphics2D.setBackground(Color.WHITE);
        graphics2D.clearRect(0, 0, width, huaBuHeight);
        //画主图
        graphics2D.drawImage(img1, 0, 0, width, height, null);
        //画二维码
        graphics2D.drawImage(qrCodeImage, width-90, height+10, 90, 90, null);
        graphics2D.setColor(Color.BLACK);
        graphics2D.setFont(new Font("微软雅黑",Font.BOLD,32));
        //绘制一行文字
        graphics2D.drawString("#找吃喝玩乐",41,996);
        //绘制下一行文字
        graphics2D.drawString("优先步刻时光#",0,1030);
        //画logo
        graphics2D.drawImage(logoImage, 0, height+10, 32, 32, null);
        graphics2D.dispose();
        return destImage;
    }

    /**
     * 生成新图片到本地
     */
    public static void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                if(!outputfile.exists()){
                    outputfile.createNewFile();
                }
                ImageIO.write(img, "png", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
